<template>
  <div>
    <a-row class="w100" style="width:600px;">
      <div class="feedtitle">亲爱的用户，您的宝贵意见和建议将帮助我们更好地提升服务质量。</div>
      <a-form :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row class="MT20">
          <a-form-item label="内容">
            <a-textarea
              class="w100"
              :autosize="false"
              style="height:120px;"
              v-decorator="['appealsContent', { rules: [{ required: true, message: '请填写您遇到的问题或意见，感谢您的支持' },{ max: 200, message: '输入内容的最大长度为200个字！'}] }]"
              placeholder="请填写您遇到的问题或意见，感谢您的支持"
            />
          </a-form-item>
        </a-row>
        <a-row>
          <div class="clearfix" style="margin-left:100px;">
            <a-upload
              :action="uploadPath"
              list-type="picture-card"
              :file-list="fileList"
              @preview="handlePreview"
              @change="handleChange"
              :beforeUpload="beforeUpload"
              accept=".image, .jpeg, .jpg, .png"
              :withCredentials="withCredentials"
              :headers="headers"
              v-decorator="['file']"
            >
              <div v-if="fileList.length < 3">
                <div v-if="showUpload">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" class="selectPhoto" :dialog-style="{ left: '-44px' }">
              <img alt="example" style="width: 100%;cursor:zoom-in" :src="previewImage"  @click="photoEnlarge(previewUrl)"/>
            </a-modal>
          </div>
          <p style="margin-left: 100px;margin-bottom: 10px;">您共上传了{{fileList.length}}张,还可上传{{3-fileList.length}}张</p>
        </a-row>
        <a-row>
          <a-form-item label="联系人">
            <a-input placeholder="请输入联系人" v-decorator="['contactUser', { rules: [{ required: phoneFlag, message: '请输入联系人' }]}]" />
<!--            <span style="color:#ff0000;">温馨提示：</span><span>留下具体联系方式以便于我们更快速地答复您的意见。</span>-->
          </a-form-item>
        </a-row>
        <a-row>
          <a-form-item label="联系方式">
            <a-input placeholder="请输入电子邮箱/联系电话" v-decorator="['contact', { rules: [{ required: phoneFlag, message: '请输入手机号或者邮箱' },
                        { validator: this.validators.validatePhoneEmail }]}]" />
            <span style="color:#ff0000;">温馨提示：</span><span>留下具体联系方式以便于我们更快速地答复您的意见。</span>
          </a-form-item>
        </a-row>
      </a-form>
      <a-row style="text-align:center;margin-bottom:20px;">
        <a-button type="primary" style="margin-right:10px;" @click="submitBtn">提交</a-button>
        <a-button :ghost="true" type="primary" @click="back()">取消</a-button>
      </a-row>
    </a-row>
  </div>
</template>
<script>
import { isEmpty } from "@/utils/func.js";
import storage from "@/utils/storage";
import { insertFeedback } from "@/api/feedback/index.js";
import {appConfig} from '../config/app'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  data(){
    return{
      phoneFlag: false,
      form: this.$form.createForm(this, { name: "feedModal" }),
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      previewVisible: false,
      previewImage: '',
      previewUrl:'',
      fileList:[],
      showUpload:true,
      fileIds:'',
      withCredentials: true,
      uploadPath:
        appConfig.microServ +
        appConfig.microServModules.file +
        "api/fdfs/file/upload",
      // headers: {
      //   Authorization: "Bearer " + sessionStorage.getItem("token")
      // },
      headers:{
        Authorization: "Bearer " + storage.session.get("authToken"),
      }
    }
  },
  created(){
    console.log('意见反馈')
    let sessionToken = sessionStorage.getItem("token");
    if(!sessionToken){
      this.phoneFlag=true;
    }
  },
  methods:{
      //图片放大效果
    photoEnlarge(val){
      console.log(val)
       window.open(val, "_blank");
    },

    submitBtn(e){
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if(isEmpty(values.appealsContent) || values.appealsContent.trim() == ''){
            this.$message.error("意见反馈内容无法为空");
            return ;
          }
          this.$set(values,'fileList',this.fileList);
          this.$emit('formVal',values)
          values.fileIds = this.fileIds;
          insertFeedback(values).then(res => {
            console.log('res',res)
            if (res.code == 0) {
              this.$emit('backModal','');
              this.$message.success("反馈成功！");
            } else {
              this.$message.error(res.data.message);
            }
          });
        }
      });
    },
    back() {
      // 调用父组件方法关闭弹窗
      // this.$parent.backModal();
      this.$emit('backModal')
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      //获取图片url用于放大回显
      console.log(file.response.data.fileUrl)
      this.previewUrl=file.response.data.fileUrl

      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      let fileIds = "";
      for (let i in fileList) {
        if (fileList[i].size != undefined && fileList[i].size / 1024 / 1024 > 2){
          fileList.splice(i, 1);
        }
        if (fileList[i].response != undefined) {
          fileIds += fileList[i].response.data.storageFileId;
          if (i != fileList.length - 1) {
            fileIds += ",";
          }
        }
      }
      this.fileList = fileList;
      this.fileIds = fileIds;
      this.showUpload = true;
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("只能上传图片文件!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小无法超过2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    // handleChange({ fileList }) {
    //   this.fileList = fileList;
    // },
  }
}
</script>

<style scoped>
.feedtitle{
  width: 100%;
  height: 50px;
  line-height: 50px;
  background: #58a7ca;
  color: #fff;
  padding-left: 5px;
}

</style>

<style >
  .selectPhoto .ant-modal-content{
  width: 800px !important;


}
</style>

